import json
import logging

from django.views import View
from django.http import JsonResponse
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema, OpenApiParameter
from rest_framework.response import Response
from rest_framework.views import APIView
from app.models import (
    User, MerchantInfo, Employee, Attendance, EmployeeActivity,
    LeaveRequest, PerformanceRecord, SalaryRecord, OrderItem, Order, Dish, Category
)
from app.models import User, MerchantInfo
from app.services.order_service import OrderService
from middleware.util import make_response
logger = logging.getLogger(__name__)
from middleware.util import  AUTH_HEADER_PARAM , parse_and_format_time




@extend_schema(
    tags=['订单模块'],
    summary='创建订单',
    description='用户创建新订单',
    parameters=[AUTH_HEADER_PARAM],
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'merchant_id': {'type': 'string', 'format': 'uuid'},
                'items': {'type': 'array', 'items': {'type': 'object'}},
                'table_number': {'type': 'string'}
            },
            'required': ['merchant_id', 'items']
        }
    },
    responses={
        201: {'description': '订单创建成功'},
        400: {'description': '请求体格式错误'},
        403: {'description': '权限不足'}
    }
)
class CreateOrderView(APIView):
    def post(self, request):
        """
        接口：创建新订单
        需要用户身份（role == 'customer'）
        URL 示例：/order/create/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'customer':
                return make_response(code=403, message="权限不足")

            data = json.loads(request.body)

            return OrderService.create_order(
                user_id=user_id,
                merchant_id=data.get("merchant_id"),
                items=data.get("items"),
                table_number=data.get("table_number")
            )

        except json.JSONDecodeError as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=['订单模块'],
    summary='对订单评分',
    description='用户对已完成订单进行评分并可上传图片',
    parameters=[AUTH_HEADER_PARAM],
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'rating': {'type': 'number'},
                'comment': {'type': 'string'},
                'images': {
                    'type': 'array',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'data': {'type': 'string'},
                            'mime_type': {'type': 'string'}
                        }
                    }
                }
            },
            'required': ['rating']
        }
    },
    responses={
        200: {'description': '评分成功'},
        400: {'description': '参数错误'},
        403: {'description': '权限不足'}
    }
)
class RateOrderView(APIView):
    def post(self, request, order_id):
        """
        接口：用户对订单评分并上传图片
        URL 示例：/order/rate/<order_id>/
        请求体示例：
        {
          "rating": 4.5,
          "comment": "很好吃，下次还会再来",
          "images": [
            { "data": "base64_string", "mime_type": "image/png" }
          ]
        }
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'customer':
                return make_response(code=403, message="权限不足")

            data = json.loads(request.body)

            return OrderService.rate_order(
                order_id=order_id,
                user_id=user_id,
                rating=data.get("rating"),
                comment=data.get("comment"),
                images=data.get("images")
            )

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)
@extend_schema(
    tags=['订单模块'],
    summary='支付订单',
    parameters=[AUTH_HEADER_PARAM],
    description='用户模拟支付订单',
    responses={
        200: {'description': '支付成功'},
        403: {'description': '权限不足'}
    }
)
class PayOrderView(APIView):
    def post(self, request, order_id):
        """
        接口：用户支付订单（模拟）
        URL 示例：/order/pay/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'customer':
                return make_response(code=403, message="权限不足")

            return OrderService.pay_order(order_id=order_id, user_id=user_id)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=['订单模块'],
    summary='取消订单',
    description='用户取消订单',
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {'description': '取消成功'},
        403: {'description': '权限不足'}
    }
)
class CancelOrderView(APIView):
    def put(self, request, order_id):
        """
        接口：用户取消订单
        URL 示例：/order/cancel/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'customer':
                return make_response(code=403, message="权限不足")

            return OrderService.cancel_order(order_id=order_id, user_id=user_id)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=["订单模块"],
    summary="获取当前用户的所有订单列表",
    description="需要 JWT Token，且角色为 customer。",
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            "description": "订单列表数据",
            "type": "object",
            "example": {
                "code": 200,
                "message": "success",
                "data": [
                    {
                        "order_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
                        "dish_name": "宫保鸡丁",
                        "price": 28.5,
                        "status": "completed"
                    }
                ]
            }
        },
        403: {"description": "权限不足"},
        500: {"description": "系统错误"}
    }
)
class ListUserOrdersView(APIView):
    def get(self, request):
        """
        接口：获取当前用户的所有订单列表
        需要 JWT Token（role == 'customer'）
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'customer':
                return make_response(code=403, message="权限不足")

            return OrderService.list_user_orders(user_id=user_id)

        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=["订单模块"],
    summary="获取某个订单的详细信息",
    description="需要 JWT Token，且角色为 customer。URL 示例：/user/order/detail/abcd1234-5678-90ef-ghij-klmnopqrstuv/",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(
            name='order_id',
            type=OpenApiTypes.UUID,
            description='订单唯一标识',
            location='path'
        )
    ],
    responses={
        200: {
            "description": "订单详细信息",
            "type": "object",
            "example": {
                "code": 200,
                "message": "success",
                "data": {
                    "order_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
                    "dish_name": "宫保鸡丁",
                    "price": 28.5,
                    "status": "completed",
                    "rating": 5,
                    "comment": "很好吃！",
                    "images": []
                }
            }
        },
        403: {"description": "权限不足"},
        404: {"description": "订单不存在"},
        500: {"description": "系统错误"}
    }
)
class GetOrderDetailView(APIView):
    def get(self, request, order_id):
        """
        接口：获取某个订单的详细信息（含评分、评论、图片）
        URL 示例：/user/order/detail/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'customer':
                return make_response(code=403, message="权限不足")

            return OrderService.get_order_detail(order_id=order_id, user_id=user_id)

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

from django.views import View
from django.http import JsonResponse
from app.services.order_service import OrderService

@extend_schema(
    tags=["商家订单管理"],
    summary="获取商家所有订单（按未完成优先排序）",
    description="需要 JWT Token，且角色为 merchant。",
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            "description": "订单列表数据",
            "type": {"type": "object", "example": {
                "code": 200,
                "message": "success",
                "data": [
                    {"order_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv", "total_price": 28.5, "status": "pending"},
                    {"order_id": "xyz12345-6789-0abc-defg-hijklmnopqrs", "total_price": 50.0, "status": "completed"}
                ]
            }}
        },
        403: {"description": "权限不足或非法商家用户"},
        500: {"description": "系统错误"}
    }
)
class ListMerchantOrdersView(APIView):
    def get(self, request):
        """
        接口：商家获取所有订单（按未完成优先排序）
        需要 JWT Token（role == 'merchant'）
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                print(user_id,role)
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return OrderService.list_merchant_orders(str(merchant_info.merchant_id))

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)
@extend_schema(
    tags=["商家订单管理"],
    summary="获取当前商家待处理订单和菜品",
    description="需要 JWT Token，且角色为 merchant。",
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            "description": "待处理订单与菜品信息",
            "type": {"type": "object", "example": {
                "code": 200,
                "message": "success",
                "data": {
                    "orders": [
                        {
                            "order_id": "abcd1234-5678-90ef-ghij-klmnopqrstuv",
                            "items": [
                                {"item_id": 1, "dish_name": "宫保鸡丁", "quantity": 2},
                                {"item_id": 2, "dish_name": "鱼香肉丝", "quantity": 1}
                            ]
                        }
                    ]
                }
            }}
        },
        403: {"description": "权限不足或非法商家用户"},
        500: {"description": "系统错误"}
    }
)
class ListPendingOrdersView(APIView):
    def get(self, request):
        """
        获取当前商家需要准备的订单和菜品
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return OrderService.list_pending_orders(str(merchant_info.merchant_id))

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=["商家订单管理"],
    summary="标记某个菜品项为已完成",
    description="需要 JWT Token，且角色为 merchant。URL 示例：/merchant/order/item/complete/123/",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(name='item_id', type=OpenApiTypes.INT, description='菜品项唯一标识', location='path')
    ],
    responses={
        200: {"description": "成功标记为已完成", "type": {"example": {"code": 200, "message": "菜品项已完成"}}},
        403: {"description": "权限不足或非法商家用户"},
        404: {"description": "菜品项不存在"},
        500: {"description": "系统错误"}
    }
)
class CompleteOrderItemView(APIView):
    def post(self, request, item_id):
        """
        标记某个菜品为已完成
        URL 示例：/merchant/order/item/complete/123/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return OrderService.complete_order_item(item_id, str(merchant_info.merchant_id))

        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

@extend_schema(
    tags=["商家订单管理"],
    summary="批量完成订单中的菜品项",
    description="需要 JWT Token，且角色为 merchant。URL 示例：/merchant/order/item/batch-complete/abcd1234-5678-90ef-ghij-klmnopqrstuv/",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(name='order_id', type=OpenApiTypes.UUID, description='订单唯一标识', location='path')
    ],
    responses={
        200: {"description": "成功完成订单中所有菜品项", "type": {"example": {"code": 200, "message": "订单菜品项全部完成"}}},
        403: {"description": "权限不足或非法商家用户"},
        404: {"description": "订单不存在"},
        500: {"description": "系统错误"}
    }
)
class BatchCompleteOrderItemsView(APIView):
    def post(self, request, order_id):
        """
        批量完成订单中的菜品
        URL 示例：/merchant/order/item/batch-complete/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return OrderService.complete_all_order_items(order_id, str(merchant_info.merchant_id))

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


from django.views import View
from django.http import JsonResponse
from app.services.order_service import OrderService

@extend_schema(
    tags=["商家订单管理"],
    summary="取消订单中所有未完成的菜品项",
    description="需要 JWT Token，且角色为 merchant。URL 示例：/merchant/order/item/cancel-all/abcd1234-5678-90ef-ghij-klmnopqrstuv/",
    parameters=[
        AUTH_HEADER_PARAM,
        OpenApiParameter(name='order_id', type=OpenApiTypes.UUID, description='订单唯一标识', location='path')
    ],
    responses={
        200: {"description": "成功取消订单中所有未完成菜品项", "type": {"example": {"code": 200, "message": "订单菜品项已取消"}}},
        403: {"description": "权限不足或非法商家用户"},
        404: {"description": "订单不存在"},
        500: {"description": "系统错误"}
    }
)
class CancelAllOrderItemsView(APIView):
    def post(self, request, order_id):
        """
        接口：商家取消订单中所有未完成的菜品项
        URL 示例：/merchant/order/item/cancel-all/abcd1234-5678-90ef-ghij-klmnopqrstuv/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            try:
                user = User.objects.get(id=user_id)
                merchant_info = MerchantInfo.objects.get(merchant_id=user_id)
            except (User.DoesNotExist, MerchantInfo.DoesNotExist):
                return make_response(code=403, message="您不是合法的商家用户")

            return OrderService.cancel_all_order_items(order_id, str(merchant_info.merchant_id))

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)
@extend_schema(
    tags=["商家订单管理"],
    summary="获取待完成菜品（按类别分组）",
    description="商家获取当前所有处于【制作中】状态的菜品，并按菜品分类进行归类展示。",
    parameters=[
        AUTH_HEADER_PARAM,
    ],
    responses={
        200: {
            "description": "成功返回待完成菜品列表",
            "example": {
                "code": 200,
                "message": "查询成功",
                "data": {
                    "热菜": [
                        {
                            "dish_name": "宫保鸡丁",
                            "quantity": 2,
                            "customization": {"辣度": "中辣"}
                        }
                    ],
                    "冷饮/小吃": []
                }
            }
        },
        403: {
            "description": "权限不足",
            "example": {
                "code": 403,
                "message": "权限不足"
            }
        },
        404: {
            "description": "商家不存在或无待处理菜品",
            "example": {
                "code": 404,
                "message": "商家不存在"
            }
        },
        500: {
            "description": "系统错误",
            "example": {
                "code": 500,
                "message": "系统错误：数据库连接失败"
            }
        }
    }
)
class GetPendingDishesByCategoryView(APIView):
    def get(self, request):
        """
        接口：商家获取当前待完成的菜品并按类别归类
        URL 示例：/merchant/pending-dishes/<merchant_id>/
        """
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)

            if not user_id or role != 'merchant':
                return make_response(code=403, message="权限不足")

            # 调用服务层方法
            response = OrderService.get_pending_dishes_by_category(merchant_id=user_id)
            return response

        except Exception as e:
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["订单管理"],
    summary="获取未制作的订单（后厨专用）",
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            "description": "获取成功",
            "example": {
                "code": 200,
                "message": "获取成功",
                "data": [
                    {
                        "category_name": "主菜",
                        "item_count": 3,
                        "items": [
                            {
                                "order_id": "123e4567-e89b-12d3-a456-426614174000",
                                "dish_id": "456e7890-e89b-12d3-a456-426614174000",
                                "dish_name": "宫保鸡丁",
                                "quantity": 2,
                                "customization": {"spicy_level": "medium"},
                                "table_number": "A01",
                                "order_time": "2024-07-04T12:30:00Z",
                                "unit_price": 28.00
                            }
                        ]
                    }
                ]
            }
        }
    }
)
class GetPendingCookOrdersView(APIView):
    def get(self, request):
        """
        获取未制作的订单项列表（按菜品类别分组）
        
        用于后厨查看需要制作的菜品
        按类别分组，便于厨师分工协作
        """
        try:
            user_id = getattr(request, 'user_id', None)
            
            if not user_id:
                return make_response(code=401, message="未登录")

            # 获取员工信息和商家ID
            try:
                employee = Employee.objects.get(user_id=user_id, employment_status='active')
                merchant_id = employee.merchant.merchant_id
            except Employee.DoesNotExist:
                return make_response(code=403, message="您不是在职员工")

            return OrderService.get_pending_cook_orders(merchant_id)

        except Exception as e:
            logger.error(f"获取未制作订单失败: user_id={user_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)


@extend_schema(
    tags=["订单管理"],
    summary="获取未上菜的订单（服务员专用）",
    parameters=[AUTH_HEADER_PARAM],
    responses={
        200: {
            "description": "获取成功",
            "example": {
                "code": 200,
                "message": "获取成功",
                "data": [
                    {
                        "category_name": "主菜",
                        "item_count": 2,
                        "items": [
                            {
                                "order_id": "123e4567-e89b-12d3-a456-426614174000",
                                "dish_id": "456e7890-e89b-12d3-a456-426614174000",
                                "dish_name": "宫保鸡丁",
                                "quantity": 2,
                                "customization": {"spicy_level": "medium"},
                                "table_number": "A01",
                                "order_time": "2024-07-04T12:30:00Z",
                                "completed_time": "2024-07-04T12:45:00Z",
                                "unit_price": 28.00
                            }
                        ]
                    }
                ]
            }
        }
    }
)
class GetPendingServeOrdersView(APIView):
    def get(self, request):
        """
        获取未上菜的订单项列表（按菜品类别分组）
        
        用于服务员查看需要上菜的菜品
        显示已制作完成但尚未上菜的订单项
        """
        try:
            print(request)
            user_id = getattr(request, 'user_id', None)
            
            if not user_id:
                return make_response(code=401, message="未登录")

            # 获取员工信息和商家ID
            try:
                employee = Employee.objects.get(user_id=user_id, employment_status='active')
                merchant_id = employee.merchant.merchant_id
            except Employee.DoesNotExist:
                return make_response(code=403, message="您不是在职员工")

            return OrderService.get_pending_serve_orders(merchant_id)

        except Exception as e:
            logger.error(f"获取未上菜订单失败: user_id={user_id}, error={str(e)}")
            return Response({
                "code": 500,
                "message": f"系统错误：{str(e)}"
            }, status=500)

